<template>
  <div id="urlImageUpload">
    <a-input-group compact style="margin-bottom: 16px">
      <a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入图片 URL" />
      <a-button type="primary" :loading="loading" @click="handleUpload" style="width: 120px">提交</a-button>
    </a-input-group>
    <div class="image">
      <img style='max-height: 480px;max-width: 480px;' v-if="image?.url" :src="image?.url" alt="img"/>
    </div>  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'

import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { uploadImageByUrlUsingPost, uploadImageUsingPost } from '@/api/imageController.ts'

// 加载参数
const loading = ref<boolean>(false)

// 该组件为受控组件，由父组件（图片创建页面）来管理
interface Props {
  image?: API.ImageVO
  spaceId?: number
  onSuccess?: (newPicture: API.ImageVO) => void
}
const props = defineProps<Props>()

/**
 * 上传
 */
const fileUrl = ref<string>()
const handleUpload = async () => {
  loading.value = true
  try {
    const params: API.ImageUploadRequest = { fileUrl: fileUrl.value }
    params.spaceId = props.spaceId;
    if (props.image) {
      params.id = props.image.id
    }
    const res = await uploadImageByUrlUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data)
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    message.error('图片上传失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
#urlImageUpload .image {
  text-align: center;
  margin-bottom: 16px;
}
</style>
